package com.pro.controller;

import com.pro.common.GuavaCommon;
import com.pro.pojo.JsMenu;
import com.pro.pojo.JsonData;
import com.pro.service.JsMenuDeptService;
import com.pro.service.JsMenuService;
import com.pro.utils.GuavaUtils;
import com.pro.utils.RedisCatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author 祖铭泽
 * @Date 2021/11/25/0025
 * @description
 */
@Controller
@RequestMapping(value = "/jsMenu")
public class JsMenuController {

    @Autowired
    private JsMenuService jsMenuService;

    @Autowired
    private GuavaUtils guavaUtils;

    @Autowired
    private JsMenuDeptService jsMenuDeptService;

    @Autowired
    private RedisCatch redisCatch;

    //查询导航栏所有内容
    @RequestMapping(value = "/getJsMenus")
    @ResponseBody
    public JsonData getJsMenus(Integer userId){
        //根据userid去查看对应的部门标识
        List<String> jsMenuDeptIdenByUserId = jsMenuDeptService.getJsMenuDeptIdenByUserId(userId);
        String deptIden="";
        //把部门标识存在一个String中作为key
        for (String s : jsMenuDeptIdenByUserId) {
            deptIden+=s;
        }
        //判断redis中是否存在这个key
        if(redisCatch.getCacheList(deptIden)==null||redisCatch.getCacheList(deptIden).isEmpty()){
            //如果key不存在
            //根据userid去查看对应的到导航栏
            List<JsMenu> jsMenuDeptByUserId = setMenus(userId);
            //把用户对应的导航栏存入redis
            redisCatch.setCacheList(deptIden,jsMenuDeptByUserId);
            return jsMenuDeptByUserId != null ? JsonData.buildSuccess(jsMenuDeptByUserId) : JsonData.buildError("服务器出错了");
        }
        //如果存在key就在redis中取
        List<Object> cacheList = redisCatch.getCacheList(deptIden);
        return cacheList != null ? JsonData.buildSuccess(cacheList) : JsonData.buildError("服务器出错了");
    }

    private List<JsMenu> setMenus(Integer userId){
        List<JsMenu> oneLevelNavs = jsMenuDeptService.getJsMenuDeptByUserId(userId,0);
        for (JsMenu oneLevelNav : oneLevelNavs) {
            oneLevelNav.setChildren(jsMenuDeptService.getJsMenuDeptByUserId(userId,oneLevelNav.getMenuId()));
            List<JsMenu> twoLevelNavs = oneLevelNav.getChildren();
            for (JsMenu twoLevelNav : twoLevelNavs) {
                twoLevelNav.setChildren(jsMenuDeptService.getJsMenuDeptByUserId(userId,twoLevelNav.getMenuId()));
            }
        }
        return oneLevelNavs;
    }
}
